<?php

// -----------------------------------------------------------------------------

include "config/config.php";
include "DBManager.php";
include "global/functions.php";
include "createDBIfNotExists.php";

$db = new DBManager($dbPath);

// -----------------------------------------------------------------------------

if (empty($_GET['plannedDate']) || empty($_GET['actualDate'])) {
    exit("需要传入有效的数据。");
}

$plannedDate = $_GET['plannedDate'];
$actualDate = $_GET['actualDate'];

//if ($plannedDate == $actualDate) {
//    exit("推迟前后日期重复。");
//}

// -----------------------------------------------------------------------------

// 取得前一天的日期。数据库查询时要用到。
// 直接筛选 >= $plannedDate 的话，会出错，$plannedDate 当日日期不会包含在结果中。
$theDayBeforePlanedDate = getTheDate($plannedDate, "-", 1);

$plannedDate = new DateTime($plannedDate);
$actualDate = new DateTime($actualDate);
$difference = $actualDate->diff($plannedDate); // 两个日期之间的差值

$difference = $difference->format('%a');
$plannedDate = $plannedDate->format('Y-m-d');
$actualDate = $actualDate->format('Y-m-d');

// -----------------------------------------------------------------------------

$sql = <<<BBB
select dateCreate from jypd
where dateCreate >= Datetime("$theDayBeforePlanedDate")
BBB;

$results = $db->query($sql);

$dates = [];
while ($row = $results->fetchArray()) {
    $dates[] = $row["dateCreate"];
}

rsort($dates); // 数组倒序排序，这步很关键

// -----------------------------------------------------------------------------
?>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>记忆片段</title>
    <link rel="stylesheet" href="resources/bootstrap-4.3.1-dist/css/bootstrap.min.css">
</head>
<body>

<!-- ----------------------------------------------------------------------- -->

<?php include 'global/globalNavBar.php'; ?>

<!-- ----------------------------------------------------------------------- -->

<div class="container mt-2">

    <?php

    try {

        foreach ($dates as $date) {

            $actualDate = getTheDate($date, '+', $difference);

            $sqlStr = <<<BBB
    update jypd
    set dateCreate = '$actualDate'
    where dateCreate = '$date'
    BBB;

            $db->exec($sqlStr);

        }

        echo '复习计划推迟成功。';

    } catch (Exception $e) {

        echo $e->getMessage();

    }

    ?>

</div>

<!-- ----------------------------------------------------------------------- -->
<script src="resources/jquery/jquery-3.4.0.min.js"></script>
<script src="resources/bootstrap-4.3.1-dist/js/bootstrap.min.js"></script>
<!-- ----------------------------------------------------------------------- -->

</body>
</html>
